package com.example.bakend.service.Impl;

import com.example.bakend.mapper.BookMapper;
import com.example.bakend.mapper.ReaderMapper;
import com.example.bakend.mapper.RecordMapper;
import com.example.bakend.pojo.*;
import com.example.bakend.service.RecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    ReaderMapper readerMapper;


    @Override
    public Integer insertRecord(Record record) {
        return recordMapper.insertRecord(record);
    }

    @Override
    public Record selectRecord(Integer id) {
        return recordMapper.selectRecord(id);
    }

//    @Override
//    public PageInfo selectRecords(Integer pageNum, Integer pageSize) {
//        PageHelper.startPage(pageNum, pageSize);
//        PageInfo pageInfo = new PageInfo();
//        List<Record> Records = recordMapper.selectRecords();
//        Page<Record> page = (Page<Record>) Records;
//        pageInfo.setTotal((int) page.getTotal());
//        pageInfo.setRows(page.getResult());
//        return pageInfo;
//
//    }

    @Override
    public PageInfo getRecords(Integer readerId, Integer bookId, LocalDateTime borrowDateBegin, LocalDateTime borrowDateEnd,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo();
        List<RecordVoReaderVoBook> Records = recordMapper.getRecords(readerId, bookId, borrowDateBegin, borrowDateEnd);
        Page<RecordVoReaderVoBook> page = (Page<RecordVoReaderVoBook>) Records;
        pageInfo.setTotal((int) page.getTotal());
        pageInfo.setRows(page.getResult());
        page.getResult().forEach(item -> {
            Integer getReaderId = item.getReaderId();
            Reader reader = null;
            if (getReaderId != null){
                reader = readerMapper.selectReader(getReaderId);
            }
            item.setReader(reader);
        });
        page.getResult().forEach(item -> {
            Integer getBookId = item.getBookId();
            Book book = null;
            if (getBookId != null){
                book = bookMapper.selectBook(getBookId);
            }
            item.setBook(book);
        });


        return pageInfo;
    }

    @Override
    public Integer deleteRecord(List<Integer> ids) {
        return recordMapper.deleteRecord(ids);
    }

    @Override
    public List<Record> selectBookIdRecord(Integer BookId) {
        return recordMapper.selectBookIdRecord(BookId);
    }

    @Override
    public Integer getRestore(Integer id) {
        return recordMapper.getRestore(id);
    }


}
